<script setup>
import headers from "~/src/components/headers.vue";
import { dayjs } from "element-plus";
import {
  getArticleTypeAPI,
  uploadImgAPI,
  uploadArticleAPI,
  getSaveArticleAPI,
} from "@/apis/publish";
import { ref, shallowRef, onBeforeUnmount, onMounted, computed } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import useDataStore from "~/src/store";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import mobilePreview from "./components/mobilePreview.vue";

defineOptions({
  name: "Publish",
});

const router = useRouter();

const dataStore = useDataStore();
const { userInfo, isMobile } = storeToRefs(dataStore);

const UPLOAD_URL = import.meta.env.VITE_UPLOAD_URL;

let photoRef = ref(null);
let typeList = ref([]); //笔记类型列表
let typeSelected = ref(null); //选中的笔记类型
let imageUrl = ref(""); // 图片的name字符串（逗号隔开）
let imgFile = ref(); // 将要真实上传的图片
// 预览的图片列表(base64)
let articlePhotoList = ref([
  {
    name: "upload",
    url: "",
  },
]);
let title = ref(); // 笔记标题
let intro = ref(); // 笔记摘要

let insertId = ref(""); // 上传到预览表的图片的id(逗号隔开)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
let valueHtml = ref();
const toolbarConfig = {
  excludeKeys: [
    "uploadImage",
    "uploadVideo",
    "fullScreen",
    "codeBlock",
    "todo",
    "insertImage",
    "insertLink",
    "insertTable",
    "viewImageLink",
    "insertVideo",
    "blockquote",
    "numberedList",
    "group-image",
    "group-video",
  ],
};
const editorConfig = { placeholder: "在这里输入笔记内容..." };

const articlePhotoListComputed = computed(() => {
  return articlePhotoList.value.filter((item) => item.name !== "upload");
});

onMounted(() => {
  getSaveArticle();
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();

  // if (title.value || intro.value || typeSelected.value || imageUrl.value || valueHtml.value) {
  //     ElMessageBox.confirm(
  //         '您有未保存的内容，是否要保存？',
  //         '提示！！',
  //         {
  //             confirmButtonText: '确定保存',
  //             cancelButtonText: '直接退出',
  //             type: 'warning',
  //         }
  //     ).then(async () => {
  //         publishAction('save')
  //     })
  // }
});

/* -------------------------------- 获取上次保存的内容 ------------------------------- */
const getSaveArticle = async () => {
  let res = await getSaveArticleAPI(userInfo.value.user_id);
  if (res.code === 200) {
    ElMessage({
      message: "已成功加载上次保存的笔记",
      type: "success",
    });
    title.value = res.data[0].article_title;
    intro.value = res.data[0].article_introduction;
    typeSelected.value = res.data[0].article_type * 1;
    imageUrl.value = res.data[0].article_coverimg
      ? res.data[0].article_coverimg + ","
      : res.data[0].article_coverimg;
    valueHtml.value = res.data[0].article_content;
    if (res.data[0].article_coverimg) {
      res.data[0].article_coverimg.split(",").forEach((item) => {
        articlePhotoList.value.push({ name: "preview", url: item });
      });
    }
  }
};

/* ------------------------------- 请求笔记所有种类信息 ------------------------------- */
const getArticleType = async () => {
  let { data } = await getArticleTypeAPI();
  typeList.value = data;
};
getArticleType();

/* ---------------------------------- 文件预览 ---------------------------------- */
/**
 * 选择文件后先自动上传到预览表，再从预览表中请求这个文件，预览为缩略图
 */
const beforeUpload = async (file) => {
  imgFile.value = file;
  let reader = new FileReader();
  // 以base64格式读取
  reader.readAsDataURL(file);
  reader.onload = (e) => {
    // imageUrl.value = e.target.result
    articlePhotoList.value.push({ name: "preview", url: e.target.result });
    ElMessage({
      message: `上传成功(最大图片数${articlePhotoList.value.length - 1}/4)`,
      type: "success",
    });
    if (articlePhotoList.value.length > 4) {
      articlePhotoList.value.shift();
    }
    setTimeout(() => {
      photoRef.value.setActiveItem(articlePhotoList.value.length - 1);
    }, 1000);
  };
};
const uploadSuccess = (response) => {
  // console.log('response', response);
  insertId.value += response.data.insertId;
  imageUrl.value += response.imgurl + ",";
  // if (imageUrl.value.endsWith(',')) {
  //     imageUrl.value = imageUrl.value.slice(0, -1)
  // }
  console.log("imageUrl", imageUrl.value);
};

/* -------------------------------- 创建富文本编辑器 -------------------------------- */
const handleCreated = (editor) => {
  editorRef.value = editor;
};

/* -------------------------------- 点击保存/发布笔记按钮 -------------------------------- */
const publishAction = async (type) => {
  debugger;
  // 笔记信息对象
  let article = {
    title: title.value,
    intro: intro.value,
    typeSelected: typeSelected.value,
    valueHtml: valueHtml.value,
    imgUrl: imageUrl.value.endsWith(",")
      ? imageUrl.value.slice(0, -1)
      : imageUrl.value,
  };
  if (type === "publish") {
    if (!article.title) return ElMessage({ message: "笔记标题不能为空" });
    if (!article.intro) return ElMessage({ message: "笔记描述不能为空" });
    if (!article.typeSelected)
      return ElMessage({ message: "笔记类型不能为空" });
    // if (!imageUrl.value) return ElMessage({ message: "笔记封面不能为空" })
    if (!article.valueHtml) return ElMessage({ message: "笔记内容不能为空" });
  }

  ElMessageBox.confirm(
    type === "publish"
      ? "笔记即将送往审核，通过后即可展示"
      : "笔记即将保存，下次可继续打开未完成的内容",
    "提示！！",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    // 用户信息对象
    let user = userInfo;
    let { data } = await uploadArticleAPI(
      article,
      user.value,
      type,
      insertId.value
    );
    if (data) {
      ElMessage({
        message:
          type === "publish" ? "上传笔记成功，正在等待审核" : "保存草稿成功",
        type: "success",
      });
      router.push({ name: "home" });
    }
  });
};
</script>

<template>
  <div class="page">
    <el-backtop :right="50" :bottom="100" />
    <div class="container">
      <div v-if="isMobile" class="mobileHeaders">
        <el-button @click="publishAction('save')">暂存笔记</el-button>
        <el-button @click="publishAction('publish')" color="#626aef"
          >发布笔记</el-button
        >
      </div>
      <div class="temp"></div>
      <div class="main">
        <div class="main-left">
          <div class="left-bread">
            <div class="left-bread-title">网页端效果预览</div>
            <div class="left-bread-btns">
              <el-button @click="publishAction('save')" color="#626aef" plain
                >暂存笔记</el-button
              >
              <el-button @click="publishAction('publish')" color="#626aef"
                >发布笔记</el-button
              >
            </div>
          </div>
          <div class="left-bread">
            <div class="bread-second-title">列表预览</div>
            <div class="bread-item">
              <div class="item-left">
                <div class="left-title">{{ title }}</div>
                <div :class="{ 'left-introduction': true }">{{ intro }}</div>
                <div class="left-author">
                  <div class="author-name">
                    {{ userInfo.user_name
                    }}<span>{{ dayjs().format("YYYY-MM-DD") }}</span>
                  </div>
                  <div class="author-lc">
                    <div><i class="iconfont icon-dianzan_kuai"></i>99</div>
                    <div><i class="iconfont icon-shoucang"></i>99</div>
                  </div>
                </div>
              </div>
              <div class="item-right" v-if="articlePhotoList.length > 1">
                <img :src="articlePhotoList[1].url" alt="" />
              </div>
            </div>
          </div>
          <div class="left-main">
            <div class="" style="margin-bottom: 20px">详情预览</div>
            <div class="left-title">
              <el-input v-model="title" placeholder="在这里输入笔记标题..." />
            </div>
            <div class="left-author">
              <div class="type">
                <div>{{ userInfo?.user_name }}</div>
                <div style="margin-left: 10px">
                  <el-select
                    v-model="typeSelected"
                    class="m-2"
                    placeholder="请选择笔记类型"
                    size="small"
                    style="width: 100px"
                  >
                    <el-option
                      v-for="item in typeList"
                      :key="item.type_id"
                      :label="item.type_name"
                      :value="item.type_id"
                    />
                  </el-select>
                </div>
              </div>
              <!-- <div>{{ nyr(new Date(articleDetail?.article_time * 1), '-') }}</div> -->
              <div>{{ dayjs().format("YYYY-MM-DD") }}</div>
            </div>
            <div class="left-intro">
              <el-input
                type="textarea"
                rows="4"
                v-model="intro"
                placeholder="在这里输入内容简介..."
              />
            </div>
            <div class="left-photos">
              <el-carousel ref="photoRef">
                <el-carousel-item v-for="item in articlePhotoList" :key="item">
                  <div v-if="item.name === 'upload'" style="height: 100%">
                    <el-upload
                      class="left-photos-uploader"
                      :action="UPLOAD_URL"
                      ::limit="4"
                      :before-upload="beforeUpload"
                      :on-success="uploadSuccess"
                      :show-file-list="false"
                      list-type="picture-card"
                    >
                      <el-icon class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </div>
                  <img v-else class="left-photos-img" :src="item.url" alt="" />
                </el-carousel-item>
              </el-carousel>
            </div>
            <div class="left-content">
              <div id="editor—wrapper1">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 500px; overflow-y: hidden"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                />
              </div>
            </div>
            <div class="left-btns">
              <div class="btn" :class="{ likeSelected: true }">
                <i class="iconfont icon-dianzan_kuai"></i>点赞
              </div>
              <div class="btn" :class="{ collectSelected: true }">
                <i class="iconfont icon-shoucang"></i>收藏
              </div>
              <div class="share">
                <div>
                  <i class="iconfont icon-qq"></i>
                  <i class="iconfont icon-weixin"></i>
                  <i class="iconfont icon-weibo"></i>
                  <i class="iconfont icon-twitter"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!isMobile" class="main-right">
          <div class="right-preview">
            <div class="preview-title">移动端效果预览</div>
            <div class="preview-effect">
              <mobile-preview
                :valueHtml="valueHtml"
                :title="title"
                :intro="intro"
                :imgUrl="imageUrl"
                :articlePhotoList="articlePhotoListComputed"
              ></mobile-preview>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import url(./publish.scss);
</style>
